function redirect(data){
	var user_id = plus.storage.getItem('user_id');
	if(user_id){
		mui.openWindow({url: data.url});
	}else{
		plus.storage.setItem('return-url', data.url);
		mui.openWindow({url: 'html/passport.html'});
	}
}

function bindPushUser(){
	var info = plus.push.getClientInfo();
	var data = {
		user_id: plus.storage.getItem('user_id'),
		client_id: plus.storage.getItem('client_id') == ''? info.clientid:plus.storage.getItem('client-id'),
		token: plus.storage.getItem('token') == ''? info.token:plus.storage.getItem('token'),
		os_type: mui.os.ios? 2:1
		// setItem('plus-status')
	};
}

function devicePushBind(){
	var plus_status = plus.storage.getItem('push-status');
	var user_id = plus.storage.getItem('user_id');
	if(plus_status == 'true'){
		return false;
	}
	if(user_id){
		return bindPushUser();
	}else{
		plusreadyPush();
	}
}

function plusreadyPush(){
	var info = plus.push.getClientInfo();
	var os_type = mui.os.ios? 2:1;
	plus.storage.setItem('os-type', os_type + '');
	plus.storage.setItem('client-id', info.clientid + '');
	plus.storage.setItem('token', info.token + '');
	var data = {
		client_id: info.clientid,
		token: info.token,
		os_type: os_type
	};
}

document.addEventListener('plusready', function(){
	plus.push.addEventListener('receive', function(msg){
		pushmessage(msg, 'receive');
	}, false);
	plus.push.addEventListener('click', function(msg){
		pushmessage(msg, 'click');
	}, false);
}, false);

function loadpushmessage(data, type){
	var webviewid = data['webviewid'];
	var sign = data['sign'];
	var jsonobj = JSON.parse(data['params']);
	for(var key in jsonobj){
		var value = jsonobj[key];
		plus.storage.setItem(key, value + '');
	}
	if(type == 'click'){
		if(sign){
			redirect({url: webviewid});
		}else{
			mui.openWindow({url: webviewid});
		}
	}else{
		plus.nativeUI.confirm('有新的推送消息啦-去看看', function(e){
			if(e.index == 0){
				redirect({url: webviewid});
			}
		}, '无忧微贷', ['确认', '取消']);
	}
}

function pushswitch(payload, type){
	if(payload.type == 'credit'){
		plus.storage.setItem('view_credit_id', payload.id + '');
		if(type == 'click'){
			mui.openWindow({url: 'html/porject.html'});
		}else{
			plus.nativeUI.confirm('有新标发布啦-去看看吧！', function(e){
				if(e.index == 0){
					mui.openWindow({url: 'html/porject.html'});
				}
			}, '无忧微贷', ['确认', '取消']);
		}
	}

	if(payload.type == 'recharge'){
		if(type == 'click'){
			redirect({url: 'html/fundsflowdetail.html'});
		}else{
			mui.alert('资金变动', '充值金额：' + payload.amount + ' 账户余额：' + payload.balance);
		}
	}
}

function pushmessage(msg, type){
	if(msg.payload){
		if(typeof(msg.payload) == 'string'){
			pushswitch(JSON.parse(msg.payload), type);
		}else{
			pushswitch(msg.payload, type);
		}
	}
}